import { Modal, message } from "ant-design-vue";
import dayjs from "dayjs";
import { Ref, computed, createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { finApprovalApi, getListApi, getPageStaticApi, statisticsDataApi, sumPriceApprovalExcelApi, simplePriceApprovalExcelListApi } from "@/api/financialManagement/singleOrderApproval/index";
import CommonHook from "@/hook/commonHook";
import { getLogApiByWaybillApi } from "@/api/waybillManagement/businessWaybill/waybillQuotation";
export default function OperationHook(state: {
  searchForm: SingleOrderApproval.SearchForm;
  tableData: Ref<Array<BusinessWaybill.ListRows>>;
  drawerOpts: Base.DrawerOpts;
  dialogOpts: Base.DialogOpts;
  loading: Ref<boolean>;
  tableRef: any;
  saPageInfo: Base.GeneraDataType;
  pageStat: Ref<Base.GeneraDataType>;
  activeKey: Ref<string>;
}) {
  const { searchForm, tableData, drawerOpts, loading, tableRef, dialogOpts, pageStat, activeKey } = state;
  const getPopupContainer = () => document.querySelector(".nav-header-page");
  const selectRows = computed<Array<ClientWaybillManagement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { getNoZeroKey } = CommonHook();
  const getData = async () => {
    const params: any = {
      ...getParams(),
      detentionStatus: null,
      status: null
    };
    if (["-5"].includes(activeKey.value)) {
      params.detentionStatus = Number(activeKey.value);
    } else {
      if (activeKey.value !== "-2") params.status = Number(activeKey.value);
    }

    loading.value = true;
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
          searchForm.beforePageNum = searchForm.pageNum;
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const pageStateic = () => {
    const params = getParams();
    return getPageStaticApi({ ...params }).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Object.assign(pageStat.value, {
          5: data[5],
          6: data[6],
          7: data[7],
          8: data[8],
          9: data[9],
          "-5": data[-5],
          "10": data[10]
        });
        activeKey.value = String(getNoZeroKey(pageStat.value, ["10", "5", "6", "7", "8", "9", "-5"]));
      }
    });
  };
  const getParams = () => {
    const {
      bizIdList,
      followIdList,
      finIdList,
      channelIdList,
      customerIdList,
      companyNames,
      customerNames,
      waybillNums,
      state,
      depositTime,
      accountPeriodIdList,
      pageNum,
      pageSize,
      beforePageNum,
      companyIdList,
      isTransferBill
    } = searchForm;
    const params: Parameters<typeof getListApi>[0] = {
      bizIdList,
      followIdList,
      customerIdList,
      state,
      accountPeriodIdList,
      channelIdList: channelIdList.length ? channelIdList.map((t: any) => t[t.length - 1]) : [],
      startDepositTime: depositTime.length ? dayjs(depositTime[0]).format("YYYY-MM-DD HH:mm:ss") : "",
      endDepositTime: depositTime.length ? dayjs(depositTime[1]).format("YYYY-MM-DD HH:mm:ss") : "",
      pageNum,
      pageSize,
      waybillNums: [],
      customerNames: [],
      companyNames: [],
      finIdList,
      total: 0,
      beforePageNum,
      companyIdList,
      isTransferBill
    };
    if (companyNames)
      params.companyNames = companyNames
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (customerNames)
      params.customerNames = customerNames
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (waybillNums)
      params.waybillNums = waybillNums
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");

    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    getData();
  };
  const showHandle = (row: SingleOrderApproval.ListRows) => {
    drawerOpts.title = `单票总价详情`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  // 审批
  const approvalHandle = (row: SingleOrderApproval.ListRows) => {
    drawerOpts.title = `审批详情`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 2;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  // 修改渠道
  const modifyChannelHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    if (selectRows.value.length > 1) return message.error("只能勾选1条运单!");
    dialogOpts.title = `修改渠道`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyChannel";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 导出
  const exportHandle = () => {
    let params: any;
    if (!selectRows.value.length) {
      params = {
        ...getParams(),
        status: activeKey.value
      };
    } else {
      params = {
        status: activeKey.value,
        list: selectRows.value
      };
    }
    return sumPriceApprovalExcelApi(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("创建任务成功，请前往导出中心下载！");
      }
    });
  };

  // 导出费用
  const exporPricetHandle = () => {
    let params: any;
    if (!selectRows.value.length) {
      params = {
        ...getParams(),
        status: activeKey.value
      };
    } else {
      params = {
        status: activeKey.value,
        list: selectRows.value
      };
    }
    return simplePriceApprovalExcelListApi(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("创建任务成功，请前往导出中心下载！");
      }
    });
  };

  // 修改材质
  const modifyMasterialHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    if (selectRows.value.length > 1) return message.error("只能勾选1条运单!");
    if (selectRows.value[0].makeInvoiceStatus === -2) return message.error("当前运单已制作发票、请修改运单发票装箱详情内产品中文名！");
    dialogOpts.title = `修改材质`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyMasterial";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 修改客户备注
  const modifyRemarkHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    dialogOpts.title = `修改客户备注`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyRemark";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 修改客户备注
  const modifyInnerRemarkHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    dialogOpts.title = `修改内部备注`;
    dialogOpts.width = "520px";
    dialogOpts.type = 2;
    dialogOpts.component = "ModifyRemark";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 批量审批
  const batchApprovalHandle = () => {
    if (!selectRows.value.length) return message.error("请先勾选运单!");
    Modal.confirm({
      title: "是否批量通过当前已选择的审批?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        return finApprovalApi({ ids: selectRows.value.map((t: any) => t.id), state: 5, refuseReason: undefined, refuseType: undefined }).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("审批成功!");
            getData();
          }
        });
      }
    });
  };
  // 查看日志
  const showLogHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    if (selectRows.value.length > 1) return message.error("只能勾选1条运单!");
    drawerOpts.title = `查看日志`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "OperationLog";
    drawerOpts.passData = selectRows.value[0];
    drawerOpts.visible = true;
  };
  // 获取日志
  const getLogFn = () => {
    return getLogApiByWaybillApi({ waybillNums: [drawerOpts.passData?.waybillNum] });
  };
  // 获取统计数据
  const getStatisticsDataFn = () => {
    const params: any = {
      ...getParams()
    };
    if (["-5"].includes(activeKey.value)) {
      params.detentionStatus = Number(activeKey.value);
    } else {
      if (activeKey.value !== "-2") params.status = Number(activeKey.value);
    }
    if (selectRows.value.length) params.list = selectRows.value;
    return statisticsDataApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        dialogOpts.passData = data || {};
      }
    });
  };
  // 查看统计
  const showStatictisHandle = () => {
    dialogOpts.title = "查看统计";
    dialogOpts.width = "900px";
    dialogOpts.component = "DataStatistics";
    dialogOpts.visible = true;
  };
  return {
    searchHandle,
    getData,
    showHandle,
    changeTabHandle,
    modifyChannelHandle,
    modifyMasterialHandle,
    exportHandle,
    modifyRemarkHandle,
    modifyInnerRemarkHandle,
    approvalHandle,
    batchApprovalHandle,
    showLogHandle,
    getLogFn,
    getStatisticsDataFn,
    showStatictisHandle,
    getPopupContainer,
    exporPricetHandle,
    getParams
  };
}
